package com.sparrow.cryptogram;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.sparrow.utils.StringUtil;

/**
 * DESede(3DES) 加密
 * 
 * @author zhanglizhi
 * @date 2012-3-18 下午08:55:34
 * @version 1.0
 */
public class ThreeDES {

	private static ThreeDES threeDES = new ThreeDES();

	public static ThreeDES getInstance() {
		return threeDES;
	}

	/**
	 * DESede(3DES)
	 */
	private final String Algorithm = "DESede";

	/**
	 * DES,DESede,Blowfish
	 * 
	 * @author zhanglizhi
	 * @date 2012-3-18
	 * @version 1.0
	 * @param src
	 *            为被加密的数据缓冲区（源）
	 * @return
	 */
	public String encrypt(String src,String secretKey) {
		try {
			byte[] bytes = src.getBytes();
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(secretKey.getBytes(), Algorithm);
			// 加密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			// 在单一方面的加密或解密
			return StringUtil.bytes2HexString(c1.doFinal(bytes));
		} catch (java.security.NoSuchAlgorithmException e1) {
			// TODO: handle exception
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @author zhanglizhi
	 * @date 2012-3-18
	 * @version 1.0
	 * @param hexStr
	 *            为加密后的缓冲区
	 * @return
	 */
	public String decrypt(String hexStr,String secretKey) {
		try {
			byte[] bytes = StringUtil.hexString2Bytes(hexStr);
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(secretKey.getBytes(), Algorithm);
			// 解密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return new String(c1.doFinal(bytes));
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}
}
